let includes = ([
    "include/common.js",

]);


let battle;

// let {getObjects,newObj,undefinedp,loadObject,objectp} = require("include/common.js");

function create() {

}

function testCombat() {

    let me = thisObject;
    if (!battle) {
        battle = newObj("clone/roundBattle.js");
        let usr = newObj("clone/user.js");
        let usr2 = newObj("clone/user.js");
        os.debug(usr);
        usr.set("asdasd", 1);
        os.debug(usr);
        usr.set("hp", 100);
        usr.set("defense", 5);
        usr2.set("hp", 100);
        usr2.set("defense", 5);

        usr.set("rdSkills", [
            100001, 100002
        ]);


        usr2.set("rdSkills", [
            100068, 100076
        ]);


        //
        battle.addKills("kill1", [usr]);
        battle.addKills("kill2", [usr2]);
        return {};
    }

    battle.heartbeat();

}

// function callConnecterOnConnect(sessionObj, msg, oper) {
//     let connecter = loadObject("adm/daemons/master/master.js");
//     if (objectp(connecter)) {
//         let agent;
//         if (oper == "") {
//             os.debug("重连加载连接对象");
//             agent = newObj("clone/agent.js");
//             agent.setSession(sessionObj);
//         } else {
//             agent = sessionObj;
//         }
//         os.debug("重连走到这儿了")
//         connecter.connect(agent, msg);
//     }
// }


// function callConnecterOnMessage(agent, msg) {
//     let connecter = loadObject("adm/daemons/master/master.js");
//     if (objectp(connecter)) {
//         connecter.onMessage(agent, msg);
//     }
// }
//

function onMessage(sessionId, str) {
    let objs = getObjects();
    let findOb = objs.filter(e => {
        if (e.get("obType") == "isAgent" && e.getSession().getSeesionId() == sessionId) {
            return e;
        }
    });
    if (findOb.length > 0) {
        let user, obj = findOb[0];
        if (!objectp(user = obj.getUser())) {
            let login = loadObject("adm/daemons/logind.js");
            if (!undefinedp(obj.inputFunc)) {
                obj.inputFunc(obj, str, obj.inputFuncArgs);
                //删除 输入函数
                // delete obj.inputFunc;
            } else {
                login.logon(obj, str);
            }
            return;
        } else {
            let connecter = loadObject("adm/daemons/master/master.js");
            if (objectp(connecter)) {
                connecter.onMessage(user, str);
            }
        }
    }

    os.debug(sessionId + " " + str);
}


function startNet() {

    let net = require("websocket");
    let gt = os.getGlobalThis();
    //gt["gameConf"] = cf;
    let port = gt["gameConf"].websocket.port;
    let ws = net.WebSocket((sk) => {

        //接受消息
        sk.on("text", (sessionId, str) => {
            onMessage(sessionId, str);
        });
        //网络关闭时
        sk.on("close", (sessionId) => {
            let user = findUserByAgent(sessionId);
            if (!objectp(user)) return;
            user.netDead();
            os.debug(`玩家${user.get("name")}的网络断开了....`);
            os.debug(`${sessionId} net close!`);
        });
        //网络错误时
        sk.on("err", (sessionId) => {
            let user = findUserByAgent(sessionId);
            if (!objectp(user)) return;
            user.netDead();
            os.debug(`玩家${user.get("name")}的网络错误....`);
            os.debug(`${sessionId} net close!`);
        });
        //网络连接状态完全就绪，已经完成open动作
        sk.on("ok", (sessionObj) => {

            let agent = newObj("clone/agent.js");
            agent.setSession(sessionObj);

            let login = loadObject("adm/daemons/logind.js");
            login.logon(agent, "");

        });

    }).listen(port);

    //writeLog("log.txt", "websocket的连接端口为：" + port.toString());
    gt["interNet"] = ws;


    os.debug(ws.getString());

}


function startHttpServer() {


    let gt = os.getGlobalThis();

    let router = os.httpServer
        .createRouter()
        //设置全局的router的Responsede的的响应类型
        .setResponseHeader("content-type", "application/json")
        .setWebRoot("www");

    //设置静态目录 静态目录是基于webRoot 所以此处的/* 不会影响restApi接口的！比如下面的test接口
    router.handler("/*", router.getStaticHandler("assest"));
    //此处的ctx需要重新单独封装,
    //handler第一个参数是接受的请求类型POST||GET 为空表示都可以,第二个参数是路由
    router.handler("post", "/test", (ctx) => {
        //ctx.params() 返回的是JSON字符串...
        let params = JSON.parse(ctx.params());
        let response = ctx.response();
        //单独设置
        response.end(JSON.stringify(params));
        os.debug("OK");
    });

    router.listen(gt["gameConf"].httpPort);
}


/**
 * 初始化指令
 */
function initCmds() {

    let files = os.fs.deepFiles("cmds");


    let gt = os.getGlobalThis();

    if (undefinedp(gt["gameCmds"])) {
        gt["gameCmds"] = {};
    }

    let path = require("path");
    for (let x in files) {
        let file = path.parse(files[x]);
        cName = file.file.split("\\.");
        cName = cName[0];
        gt["gameCmds"][cName] = file.filePath;
    }
    os.debug("load cmds :" + JSON.stringify(gt["gameCmds"]));

}

function main() {


    startNet();
    startHttpServer();
    initCmds();
    os.debug("gameStart.....");


    //永恒的循环.....
    while (true) {
        //1.5s 心跳一次
        Worker.sleep(3000);

        let obs = getObjects();
        for (let i in obs) {
            if (undefinedp(obs[i].get)) continue;
            if (undefinedp(obs[i].heartbeat)) continue;
            if (obs[i].get("heartbeat")) {
                obs[i].heartbeat();
            }
        }
    }

}


function teststment() {

    //  let userxx = newObj("clone/user.js");
    // userxx.receiveDamage("hp",1);
    // os.debug(userxx);
    //D("test/testdb.js").heartbeat();

    // os.debug(userxx,"看看导入对象咋样...");
    //
    //D(FIX_ROUND_D).heartbeat();
// os.debug("asdasd");
    // me.testCombat();
    // if(x!=1){
    //     httpTest();
    //     x=1;
    // }

    //  let data = os.db.select("select * from w_users where id=8442");

    // let data = os.db.add("insert into w_users (username)VALUE('faros测试')");
    // os.debug(data);
    // data = JSON.parse(data);
    // os.debug(data[0].id);
    //os.debug(os.time.timeMillis());
    //D("test/testtime.js").timeMills();
    //D("test/db.js").insert();
}


